package cn.cvs.controller;

import cn.cvs.pojo.Supplier;
import cn.cvs.pojo.SysUser;
import cn.cvs.service.storageRecord.StroageRecordService;
import cn.cvs.service.supplier.SupplierService;
import cn.cvs.utils.Constants;
import cn.cvs.utils.PageSupport;
import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FilenameUtils;

import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/sys/supplier/")
public class SupplierController {

    private static final Logger logger = Logger.getLogger(SupplierController.class);
    @Resource
    private SupplierService supplierService;

    @Resource
    private StroageRecordService stroageRecordService;


    /**
     * Ajax下拉框同步供应商列表
     * @return
     */
    @ResponseBody
    @GetMapping(value = "simpleList",produces = {"aplication/json;charset=UTF-8"})
    public Object simpleList() throws Exception {
        System.out.println("进入查询供应商列表方法");
        List<Supplier> supplierList = supplierService.findAllSupplier();
        return JSON.toJSONString(supplierList);
    }

    @RequestMapping("/list")
    public String supplierList(@RequestParam(value = "pageIndex", required = false) String pageIndex,
                               @RequestParam(value = "querySupCode", required = false) String querySupCode,
                               @RequestParam(value = "querySupName", required = false) String querySupName,
                               Model model) throws Exception {
        Integer currentPageNo = 1;
        if (pageIndex != null && !"".equals(pageIndex)) {
            currentPageNo = Integer.valueOf(pageIndex);
        }
        Integer totalCount = supplierService.totalCount(querySupCode, querySupName);
        Integer pageSize = Constants.pageSize;
        PageSupport pageSupport = new PageSupport();
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);
        int totalPageCount = pageSupport.getTotalPageCount();
        if (currentPageNo < 1) {
            currentPageNo = 1;
        } else if (currentPageNo > totalPageCount) {
            currentPageNo = totalPageCount;
        }
        List<Supplier> supplierList = supplierService.findAllSupplier(currentPageNo, pageSize, querySupCode, querySupName);
        model.addAttribute("supplierList", supplierList);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("querySupCode", querySupCode);
        model.addAttribute("querySupName", querySupName);
        model.addAttribute("currentPageNo", currentPageNo);
        model.addAttribute("totalPageCount", totalPageCount);
        return "supplier/list";
    }

    @RequestMapping("/toAdd")
    public String toAdd(){
        return "supplier/add";
    }

    @PostMapping("/add")
    public String add(Supplier supplier, HttpSession session, HttpServletRequest request, @RequestParam(value = "attachs", required = false) MultipartFile[] attachs) throws Exception {
        String companyLicPicPath = null;
        String orgCodePicPath = null;
        String errorInfo = null;
        boolean flag = true;
        String path = session.getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
        logger.info("文件存储路径：" + path);
        for (int i = 0; i < attachs.length; i++) {
            MultipartFile attach = attachs[i];
            if (!attach.isEmpty()) {
                if (i == 0) {
                    errorInfo = "uploadFileError";
                } else if (i == 1) {
                    errorInfo = "uploadOcError";
                }
                String oldFileName = attach.getOriginalFilename();//原文件名
                logger.info("原文件名：" + oldFileName);//原文件后缀
                String prefix = FilenameUtils.getExtension(oldFileName);
                logger.info("原文件名后缀：" + prefix);
                int filesize = 150000000;
                logger.info("上传文件大小：" + attach.getSize());
                if (attach.getSize() > filesize) {//上传大小不得超过500KB
                    request.setAttribute(errorInfo, " * 上传大小不得超过1500000KB");
                    flag = false;
                } else if (prefix.equalsIgnoreCase("jpg")
                        || prefix.equalsIgnoreCase("png")
                        || prefix.equalsIgnoreCase("jpeg")
                        || prefix.equalsIgnoreCase("pneg")) {//上传图片格式不正确
                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(150000000) + "_Personal." + prefix;
                    logger.info("新文件名称：" + fileName);
                    File targetFile = new File(path);
                    if (!targetFile.exists()) {
                        targetFile.mkdirs();
                    }
                    //保存
                    try {
                        attach.transferTo(new File(targetFile, fileName));
                    } catch (Exception e) {
                        e.printStackTrace();
                        request.setAttribute(errorInfo, " * 上传失败！");
                        flag = false;
                    }
                    if (i == 0) {
                        companyLicPicPath = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
                    } else if (i == 1) {
                        orgCodePicPath = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
                    }
                    logger.info("companyLicPicPath：" + companyLicPicPath);
                    logger.info("orgCodePicPath：" + orgCodePicPath);
                } else {
                    request.setAttribute(errorInfo, " * 上传图片格式不正确");
                    flag = false;
                }
            }
        }
        if (flag) {
            logger.info("进入添加供应商方法，参数：" + supplier);
            supplier.setCreatedUserId(((SysUser) session.getAttribute(Constants.USER_SESSION)).getId());
            supplier.setCompanyLicPicPath(companyLicPicPath);
            supplier.setOrgCodePicPath(orgCodePicPath);
            if (supplierService.addSupplier(supplier)) {
                return "redirect:/sys/supplier/list";
            }
        }
        return "supplier/add";
    }

    @RequestMapping("/toUpdate/{supId}")
    public String toUpdate(@PathVariable("supId") String supId, Model model) throws Exception {
        Supplier supplier = supplierService.findSupplierById(supId);
        model.addAttribute("supplier",supplier);
        return "supplier/update";
    }

    @PostMapping("/update")
    public String update(Supplier supplier, HttpSession session, HttpServletRequest request, @RequestParam(value = "attachs", required = false) MultipartFile[] attachs) throws Exception {
        String companyLicPicPath = null;
        String orgCodePicPath = null;
        String errorInfo = null;
        boolean flag = true;
        String path = session.getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
        logger.info("文件存储路径：" + path);
        for (int i = 0; i < attachs.length; i++) {
            MultipartFile attach = attachs[i];
            if (!attach.isEmpty()) {
                if (i == 0) {
                    errorInfo = "uploadFileError";
                } else if (i == 1) {
                    errorInfo = "uploadOcError";
                }
                String oldFileName = attach.getOriginalFilename();//原文件名
                logger.info("原文件名：" + oldFileName);//原文件后缀
                String prefix = FilenameUtils.getExtension(oldFileName);
                logger.info("原文件名后缀：" + prefix);
                int filesize = 150000000;
                logger.info("上传文件大小：" + attach.getSize());
                if (attach.getSize() > filesize) {//上传大小不得超过500KB
                    request.setAttribute(errorInfo, " * 上传大小不得超过1500000KB");
                    flag = false;
                } else if (prefix.equalsIgnoreCase("jpg")
                        || prefix.equalsIgnoreCase("png")
                        || prefix.equalsIgnoreCase("jpeg")
                        || prefix.equalsIgnoreCase("pneg")) {//上传图片格式不正确
                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(150000000) + "_Personal." + prefix;
                    logger.info("新文件名称：" + fileName);
                    File targetFile = new File(path);
                    if (!targetFile.exists()) {
                        targetFile.mkdirs();
                    }
                    //保存
                    try {
                        attach.transferTo(new File(targetFile, fileName));
                    } catch (Exception e) {
                        e.printStackTrace();
                        request.setAttribute(errorInfo, " * 上传失败！");
                        flag = false;
                    }
                    if (i == 0) {
                        companyLicPicPath = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
                    } else if (i == 1) {
                        orgCodePicPath = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
                    }
                    logger.info("companyLicPicPath：" + companyLicPicPath);
                    logger.info("orgCodePicPath：" + orgCodePicPath);
                } else {
                    request.setAttribute(errorInfo, " * 上传图片格式不正确");
                    flag = false;
                }
            }
        }
        if (flag) {
            logger.info("进入修改供应商方法，参数：" + supplier);
            supplier.setUpdatedUserId(((SysUser) session.getAttribute(Constants.USER_SESSION)).getId());
            supplier.setCompanyLicPicPath(companyLicPicPath);
            supplier.setOrgCodePicPath(orgCodePicPath);
            if (supplierService.updateSupplier(supplier)) {
                return "redirect:/sys/supplier/list";
            }
        }
        return "supplier/update";
    }

    @RequestMapping("/view/{supId}")
    public String view(@PathVariable String supId, Model model) throws Exception {
        logger.info("进入供应商详情页面");
        Supplier supplier = supplierService.findSupplierById(supId);
        model.addAttribute("supplier", supplier);
        return "/supplier/view";
    }

    /**
     * Ajax删除供货商信息
     * @param uid
     */
    @ResponseBody
    @DeleteMapping("/del/{uid}")
    public Object del(@PathVariable String uid) throws Exception {
        logger.info("进入删除用户供货商信息方法，参数"+uid);
        HashMap<String,Object> resultMap = new HashMap<String, Object>();
        Supplier supplier = supplierService.findSupplierById(uid);
        if (supplier == null){//判断该用户是否存在
            resultMap.put("delResult","notexist");
        }else {
            if (supplierService.deleteSupplier(uid)){//判断是否删除成功
                resultMap.put("delResult","true");
            }else {
                resultMap.put("delResult","false");
            }
        }
        return JSON.toJSONString(resultMap);
    }
}
